﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Configuration;
using System.Net;

namespace NibbleOil.Web.Business.Helper
{
    public class Mail
    {

        public static bool SendMail(string from, string to, string subject, string body)
        {
            MailMessage mailObj = new MailMessage(from, to, subject, body);
            mailObj.IsBodyHtml = true;

            SmtpClient SMTPServer = new SmtpClient();

            if (!string.IsNullOrEmpty(Business.Helper.Parameter.GetValue(Enumeration.ParameterEnum.Name.SmtpServerHost)))
                SMTPServer.Host = Business.Helper.Parameter.GetValue(Enumeration.ParameterEnum.Name.SmtpServerHost);

            if ( !string.IsNullOrEmpty(Business.Helper.Parameter.GetValue(Enumeration.ParameterEnum.Name.SmtpServerPort)))
                SMTPServer.Port = int.Parse(Business.Helper.Parameter.GetValue(Enumeration.ParameterEnum.Name.SmtpServerPort));

            if (!string.IsNullOrEmpty(Business.Helper.Parameter.GetValue(Enumeration.ParameterEnum.Name.EmailCredentialUser)) &&
                !string.IsNullOrEmpty(Business.Helper.Parameter.GetValue(Enumeration.ParameterEnum.Name.EmailCredentialPass)))
            {
                string sUser = Business.Helper.Parameter.GetValue(Enumeration.ParameterEnum.Name.EmailCredentialUser);
                string sPass = Business.Helper.Parameter.GetValue(Enumeration.ParameterEnum.Name.EmailCredentialPass);

                SMTPServer.Credentials = new NetworkCredential(sUser, sPass);
            }

            if (!string.IsNullOrEmpty(Business.Helper.Parameter.GetValue(Enumeration.ParameterEnum.Name.SmtpServerSsl)))
                SMTPServer.EnableSsl = bool.Parse(Business.Helper.Parameter.GetValue(Enumeration.ParameterEnum.Name.SmtpServerSsl));

            
            try
            {
                SMTPServer.Send(mailObj);
            }
            catch(Exception ex)
            {
                LogError.WriteError(ex);
                return false;
            }

            return true;
        }
    }
}
